const {
    arrayToMap,
    dateFormat,
    CombinedPredicate: {
        not,
        and,
    },
    stringValidator: {
        isIpv4,
        isEmpty,
    },
    AsyncArray,
    compare,
} = rx

const validate = (() => {
    let checkIpArr = (start, end) => (_v, form) => {
        const fn = name => form[name].split('.').slice(0, 3)
        return !compare(fn(start), fn(end))
    }
    let checkIpLast = (start, end) => (_v, form) => {
        const last = name => form[name].split('.')[3]
        return last(start) > last(end)
    }
    const {notBlank, create} = RxElemValidator
    let isIpSegment = (_v, {authType}) => authType === 2
    return RxFormValidator.generate([
        notBlank('startIp', '[起始 ip 地址] 不能为空'),
        create('startIp', '[起始 ip 地址] 格式错误，示例: 192.168.1.1', not(isIpv4)),
        create('endIp', '[终止 ip 地址] 格式错误，示例: 192.168.1.255', and(isIpSegment, not(isIpv4))),
        create('endIp', '[起始 ip 地址] 和 [终止 ip 地址] 必须在同一网段下（前三位相同），示例: [192.168.1.1, 192.168.1.255]', and(isIpSegment, checkIpArr('startIp', 'endIp'))),
        create('endIp', '[终止 ip 地址] 最后一位的地址必须大于 [起始 ip 地址]，示例: [192.168.1.1, 192.168.1.255]', and(isIpSegment, checkIpLast('startIp', 'endIp'))),
    ])
})()

/**
 * @author rxliuli
 */
const app = (() => {
        const allowIpEnableKey = 'allow_ip_enable'
        return new Vue({
            el: '#app',
            data() {
                return {
                    sysUserCount: 0,
                    sysUserList: [],
                    sysRoleList: [],
                    sysRoleMap: new Map(),
                    sysAuthIpSegList: [],
                    currentIp: '',
                    allowIpEnable: new SystemConfig({configKey: allowIpEnableKey}),
                    allowIpEnableMap: new Map()
                        .set(1, '关闭')
                        .set(2, '启用'),
                    searchText: '',
                }
            },
            methods: {
                editUser(sysUser) {
                    forward('/system-config/modify/admin_privilege_admin_edit', sysUser)
                },
                async deleteUser(id) {
                    const confirmResult = await rxPrompt.confirm('确定要删除么？', ['确定', '取消'])
                    if (!confirmResult) {
                        return
                    }
                    const deleteResult = await ajaxOption({
                        res: sysUserApi.delete(id),
                        danger: '删除失败',
                        success: '删除成功',
                    })
                    if (deleteResult) {
                        this.sysUserCount = await sysUserApi.count()
                        this.sysUserList = await sysUserApi.listByLastCount(5)
                        this.sysRoleList = await sysRoleApi.listForAll()
                    }
                },
                editRole(sysRole) {
                    forward('/system-config/modify/admin_privilege_group_edit', sysRole)
                },
                addRole(){
                    forward('/system-config/add/admin_privilege_group_add')
                },
                async deleteRole(id) {
                    const confirmResult = await rxPrompt.confirm('确认删除么？', ['确认', '取消'])
                    if (!confirmResult) {
                        return
                    }
                    const res = await ajaxOption({
                        res: sysRoleApi.delete(id),
                        danger: '删除失败',
                        success: '删除成功',
                    })
                    if (res) {
                        this.sysRoleList = await sysRoleApi.listForAll()
                    }
                },
                deleteSysAuthIpSeg(i) {
                    this.sysAuthIpSegList.splice(i, 1)
                },
                async updateSysAuthIpSeg() {
                    if (await AsyncArray.from(this.sysAuthIpSegList).every(validate) && await ajaxOption({
                        res: sysAuthIpSegApi.updateBatch(this.sysAuthIpSegList),
                        danger: '更新授权 ip 地址失败',
                        success: '更新授权 ip 地址成功',
                    })) {
                        this.sysAuthIpSegList = await sysAuthIpSegApi.listForAll()
                    }
                },
                addIp(authType) {
                    this.sysAuthIpSegList.push(new SysAuthIpSeg({
                        authType,
                    }))
                },
                async updateAllowIpEnable() {
                    const {configKey, configValue} = this.allowIpEnable
                    await ajaxOption({
                        res: sysConfigurationApi.updateByKey(configKey, configValue),
                        danger: '修改是否启用授权 ip 状态失败',
                        success: '修改是否启用授权 ip 状态成功',
                    })
                },
                dateFormat(date) {
                    return dateFormat(new Date(date), 'yyyy-MM-dd hh:mm:ss')
                },
                async currentIpInit() {
                    this.currentIp = await commonApi.currentIp()
                },
                async sysUserCountInit() {
                    this.sysUserCount = await sysUserApi.count()
                },
                async sysUserListInit() {
                    this.sysUserList = await sysUserApi.listByLastCount(5)
                },
                async sysRoleListInit() {
                    this.sysRoleList = await sysRoleApi.listForAll()
                    this.sysRoleMap = arrayToMap(this.sysRoleList, ({id}) => id, ({name}) => name)
                },
                async sysAuthIpSegListInit() {
                    this.sysAuthIpSegList = await sysAuthIpSegApi.listForAll()
                },
                async allowIpEnableInit() {
                    const allowIpEnable = await sysConfigurationApi.getByKey(allowIpEnableKey)
                    if (allowIpEnable) {
                        this.allowIpEnable = allowIpEnable
                    }
                },
                async init() {
                    this.currentIpInit()
                    this.sysUserCountInit()
                    this.sysUserListInit()
                    this.sysRoleListInit()
                    this.sysAuthIpSegListInit()
                    this.allowIpEnableInit()
                },
            },
            computed: {
                fieldFormatter() {
                    return fieldFormatter
                },
            },
            async mounted() {
                await this.init()
            },
        })
    }
)()